<?php
/**
 * PHPECS社交电商系统，使用thinkphp框架+MySQL数据库编写的小程序商城系统，基于LGPL协议开源授权
 * @package phpecs
 * @author qq(123865789)
 * @copyright 2018-2020 深圳塔灯网络科技有限公司
 * @version 2.0
 * @license http://www.phpecs.com/lgpl.html phpecs开源授权协议：GNU Lesser General Public License
 **/
namespace app\admin\model\store;
use app\admin\model\activity\ActivityList;
use think\Model;
class StoreProduct extends Model{

    /**
     * 获取商品某一个字段
     * @param string $where
     * @param null $field
     * @return mixed
     */
    public static function getField($where, $field, $type = 0){
        if ($type == 0){
            return self::where($where)->value($field);
        }else{
            return self::where($where)->column($field);
        }
    }

    /**
     * 查找数据
     * @param $where
     * @param $field
     * @param $page
     * @param $limit
     * @param string $order
     * @return array
     */
    public static function selProductZhi($where, $field, $page, $limit, $is_jin = 0, $order = 'time desc'){
        $data = self::whereProduct($where)->field($field)->order($order)->limit($page, $limit)->select();
        foreach ($data as $k => $v){
            $data[$k]['img'] = StoreProductImg::getField(['pid' => $v['id']], 'img');
            if ($is_jin == 1){
                $jin = ActivityList::is_jin($v['id']);
                if ($jin) unset($data[$k]);
            }
        }
        $count = self::whereProduct($where)->count();
        $list = [
            'data' => $data,
            'count' => $count
        ];
        return $list;
    }

    /**
     * 条件
     * @param $where
     * @return $this
     */
    public static function whereProduct($where){
        return self::where($where);
    }

    /**
     * 修改某个字段
     * @param $where
     * @param $field
     * @param $value
     * @return int
     */
    public static function upField($where, $field, $value){
        return self::where($where)->setField($field, $value);
    }

    /**
     * 查询一条数据
     * @param $where
     * @param string $field
     * @return array|false|\PDOStatement|string|Model
     */
    public static function getProductInfo($where, $field = ''){
        return self::where($where)->field($field)->find();
    }

    /**
     * 添加一条数据
     * @param mixed|string $data
     * @return int|string
     */
    public static function add($data){
        return self::insertGetId($data);
    }

    /**
     * 修改一条数据
     * @param $where
     * @param $data
     * @return $this
     */
    public static function edit($where, $data){
        return self::where($where)->update($data);
    }

    /**
     * 删除一条数据
     * @param $where
     * @return int
     */
    public static function del($where){
        return self::where($where)->delete();
    }

    /**
     * 查出为nul 和 空的数据id
     * @return array
     */
    public static function isNullId(){
        return self::whereNull('sp_code')->whereOr('sp_code', '')->column('id');
    }

    /**
     * 事务生成商品二维码
     * @param $ids
     */
    public static function trans($ids){
        // 启动事务
        self::startTrans();
        try{
            foreach ($ids as $k => $v){
                $access_token = access_token();
                $scene = "shop_id:$v";
                $img = createImg($access_token, $scene);
                $name = $v.'-'.time();
                file_put_contents('uploads/shop/sp-'.$name.'.png', $img);
                //存储二维码路径
                $img_url = 'uploads/shop/sp-'.$name.'.png';
                $res = StoreProduct::upField(['id' => $v], 'sp_code', $img_url);
                if (!$res) {
                    throw new \Exception("数据错误");
                }
            }
            // 提交事务
            self::commit();
            echo json_encode(array('info' => 1, 'msg' => '更新成功'));
        } catch (\Exception $e) {
            // 回滚事务
            self::rollback();
            echo json_encode(array('info' => 0, 'msg' => $e->getMessage()));
        }
    }

    /**
     * 查询出数据
     * @param $where
     * @param string $field
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function selProduct($where, $field = ''){
        return self::where($where)->field($field)->select();
    }

    /**
     * 根据条件统计数据
     * @return int|string
     */
    public static function countProduct($where){
        return self::where($where)->count();
    }

    /**
     * 返回ECharts查询数据
     * @param $status
     * @param string $order
     * @return array
     */
    public static function selProductECharts($status, $dateTime, $order = 'time asc'){
        $min = self::where('is_del', 0)->min('time');
        $minTime = $min ? strtotime(date('Y-m-d', $min)) : time(); //数据库里面最小的时间
        if ($status == 5){
            $dateTime = explode(' - ', $dateTime);
            $start = strtotime($dateTime[0]) < $minTime ? $minTime : strtotime($dateTime[0]);
            $end = strtotime($dateTime[1]) + 86399; //结束时间是日期按当天最后一秒算
            $where['time'] = [['egt', $start], ['elt', $end]];
            $day = ceil((($end - $start) / 86400)); //计算有多少天
        }else{
            $start = TimeAssign($status); //开始时间
            if ($start) {
                $where['time'] = ['egt', $start];
                //如果小于数据库最小时间直接使用数据库最小时间开始组合
                $start = $start < $minTime ? $minTime : $start;
            }else{
                $start = $minTime;
            }
            $day = ceil(((time() - $start) / 86400)); //计算有多少天
        }
        $data = self::where($where)->where('is_del', 0)->field('id, time')->order($order)->select();
        $data2 = StoreOrder::selOrderNum($where);
        $arr = []; //新的数组
        for ($i = 0; $i < $day; $i++){
            $startTime = $start + 86400 * $i; //每天开始时间戳
            $endTime = $start + 86400 * $i + 86400; //每天结束时间戳
            $daily = date('Y-m-d', $startTime); //每天的日期
            $arr[$daily]['count'] = 0; //条数
            $arr[$daily]['num'] = 0; //当天销量
            foreach ($data as $k => $v){
                if ($v['time'] >= $startTime && $v['time'] < $endTime){
                    $arr[$daily]['count'] += 1;
                }
            }
            foreach ($data2 as $k => $v){
                if ($v['time'] >= $startTime && $v['time'] < $endTime){
                    $arr[$daily]['num'] += $v['num'];
                }
            }
        }
        $count['whole'] = self::where('is_del', 0)->count(); //商品总条数
        $count['news'] = self::where('is_del', 0)->where($where)->count(); //商品总条数
        $count['shortage'] = self::where('stock', 0)->count(); //缺货条数
        $count['lower'] = self::where('status', 1)->count(); //下架商品
        $count['is_del'] = self::where('is_del', 1)->count(); //回收站
        //销售排行
        $where['status'] = ['neq', 0]; //去除掉待支付的
        $oid = StoreOrder::getField($where, 'id', 1); //查询当前时间条件对应的订单id
        if ($oid){
            $where3['oid'] = ['in', $oid];
            $ranking['count'] = StoreOrderList::countOrderList($where3, 'num'); //总数量
            $ranking['money'] = StoreOrderList::sumOrderList($where3, 'unit*num'); //总价格
            $data3 = StoreOrderList::selOrderListSort($where3);
            foreach ($data3 as $k => $v){
                //商品名称和销售所占百分比
                $data3[$k]['name'] = self::getField(['id' => $v['pid']], 'name');
                $data3[$k]['scale'] = round($v['num'] / $ranking['count'] * 100, 2); //乘以一百转换为百分比
                switch ($k){ //根据排名先后更换class
                    case 0:
                        $class = 'layui-bg-red';
                        break;
                    case 1:
                        $class = 'layui-bg-orange';
                        break;
                    case 2:
                        $class = 'layui-bg-green';
                        break;
                    case 3:
                        $class = 'layui-bg-cyan';
                        break;
                    case 4:
                        $class = 'layui-bg-blue';
                        break;
                    default:
                        $class = 'layui-bg-blue';
                        break;
                }
                $data3[$k]['class'] = $class;
            }
            $ranking['data'] = $data3;
        }
        return compact('arr', 'count', 'ranking');
    }
}